import express from "express"
//导入参数中间件
import bodyParser from "body-parser"
import bodyParserErrorHandler from "express-body-parser-error-handler"
import { JWT } from "./utils/token"
//引入定時任務
import { shedule } from "./schedule"
const cors = require('cors')


//导入log
import { logger } from "./utils"

//导入express类型
import type { Request, Response, Application } from "express"

const app: Application = express()
//const router: Router = express.Router()

//端口号
const port: string = "5050"
//导入路由
import useRoutes from "./routes"

//设置中间件,抓取参数
// app.use(bodyParser.urlencoded({ extended: false }))
// app.use(bodyParser.json())

app.use(bodyParser.json({ limit: "5000mb" }))
app.use(bodyParser.urlencoded({ limit: "5000mb", extended: true }))
app.use(bodyParserErrorHandler())
app.use(cors())
//啟動定時任務
shedule.init()

/**
 * @description: 设置允许跨域
 * @param {Request} req
 * @param {Response} res
 * @param {*} next
 * @return {*}
 */
app.all("*", (req: Request, res: Response, next) => {
  //設置請求頭格式，允許跨域
  res.header("Access-Control-Allow-Origin", "*")
  res.header(
    "Access-Control-Allow-Methods",
    "GET, POST ,OPTIONS , PUT, PATCH, DELETE"
  )
  res.header(
    "Access-Control-Allow-Headers",
    "x-access-token, Origin, X-Requested-With, Content-Type, Accept"
  )
  logger.trace(req.url)
  if (req.method.toLocaleLowerCase() === "options") {
    res.status(204).send({})
    //return res.json({}) //直接返回空数据，结束此次请求
  }
  //token驗證。未通過認證直接403
  else if(!JWT.verifytoken(req.headers.authorization)  && req.url.split('/')[1] ==="material" && req.url.split('/')[2] !=="author"){
    res.status(403).send({code:403, message:"登錄失效，請重新登錄"})
  }
  else {
    next()
  }
})

//执行所有路由函数
useRoutes(app)

//设置404
app.all("*", (_req: Request, res: Response) =>
  res.status(404).send({ code: 0, message: "no such url" })
)

app.listen(port, (): void => {
  console.log(`後台已啟動，端口：${port}`)
})
